<template>
  <el-dialog
    v-if="isOpen"
    title="立项尽调设置"
    :visible.sync="isOpen"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    width="750px"
    append-to-body
    @close="close"
  >
    <el-form
      ref="form"
      :model="formData"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item
        label="选择部门"
        prop="department_id"
      >
        <el-cascader
          ref="department"
          v-model="formData.department_id"
          class="department-select"
          :disabled="selectDisabled"
          :options="deptOptions"
          placeholder="请选择部门"
          :show-all-levels="false"
          :props="{ expandTrigger: 'hover',checkStrictly: true , emitPath: false,label:'department_name',value:'id'}"
          @change="departmentChange"
        />
      </el-form-item>
      <el-form-item
        label="项目类型"
        prop="project_type_id"
      >
        <el-select
          v-model="formData.project_type_id"
          placeholder="请选择项目类型"
          clearable
          :style="{ width: '100%' }"
          @change="projectTypeChange"
        >
          <el-option
            v-for="(item, index) in projectTypeOptions"
            :key="index"
            :label="item.dict_val"
            :value="item.id"
            :disabled="item.disabled"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="填写信息"
        prop="tem_content.label_info"
      >
        <el-button
          type="text"
          icon="el-icon-plus"
          size="medium"
          @click="addItem"
        >添加</el-button>
      </el-form-item>
      <el-form-item label="">
        <el-table
          :data="formData.tem_content.label_info"
          border
          size="medium"
          style="width: 100%"
        >
          <el-table-column
            prop="date"
            label="显示标题名称"
            align="center"
          >
            <template slot-scope="scope">
              <el-form-item
                class="name-form-item"
                :prop="'tem_content.label_info.'+scope.$index+'.label_key'"
                :rules="[{ required: true, message: '请输入标题名称', trigger: 'blur' },{ validator: labelKeyPass(scope.$index), trigger: 'blur' }]"
              >
                <el-input
                  v-model="scope.row.label_key"
                  type="text"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="是否必填"
            align="center"
            width="120px"
          >
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.if_required">必填</el-checkbox>
            </template>
          </el-table-column>
          <el-table-column
            label="输入框类型"
            align="left"
            header-align="center"
          >
            <template slot-scope="scope">
              <el-radio
                v-model="scope.row.label_type"
                label="textarea"
              >多行输入框</el-radio>
              <el-radio
                v-model="scope.row.label_type"
                label="richtext"
                text-color="#333"
              >富文本
              </el-radio>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="120px"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-delete"
                size="medium"
                @click="removeItem(scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <div
      slot="footer"
      class="dialog-footer"
    >
      <el-button @click="close">取 消</el-button>
      <el-button
        type="primary"
        @click="submitForm"
      >确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  departmentList,
  creatLookInfoModel,
  editLookInfoModel,
  departmentModelDetail
} from '@/api/lookInfoModel'
export default {
  props: {
    id: {
      type: String,
      default: () => {}
    },
    listDepartmentId: {
      type: Array,
      default: () => {}
    }
  },

  data() {
    var projectTypePass = (rule, value, callback) => {
      callback()
    }
    return {
      isOpen: false,
      queryParams: {
        department_name: '',
        department_status: null
      },
      projectTypeOptions: [],
      formData: {
        project_type_id: '',
        department_name: '',
        department_id: '',
        tem_content: {
          label_info: []
        }
      },
      deptOptions: [],
      selectDisabled: false,
      // 弹框
      rules: {
        department_id: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        project_type_id: [
          {
            required: true,
            validator: projectTypePass,
            message: '请选择项目类型',
            trigger: 'change'
          }
        ],
        'tem_content.label_info': [
          {
            type: 'array',
            required: true,
            message: '请添加填写信息',
            trigger: 'change'
          }
        ]
      }
    }
  },
  // 生命周期 - 创建完成（访问当前this实例）
  created() {
    console.log(this.formData)
  },
  methods: {
    getSysAllDic() {
      var projectTypeList = []
      this.projectTypeOptions = []
      let allDic = this.$store.getters.sysDic()
      if (!allDic) {
        this.$store.dispatch('sys/getSysAllDic').then((data) => {
          allDic = data
        })
      }
      projectTypeList = allDic['project_type'] || []
      var item = {
        id: '',
        dict_key: '全部',
        dict_type: 'project_type',
        dict_val: '全部'
      }
      this.projectTypeOptions = [item, ...projectTypeList]
    },
    // 项目类型改变
    projectTypeChange(val) {
      const obj = this.projectTypeOptions.find((itm) => {
        return itm.id === val
      })
      this.formData.project_type = obj.dict_val
      console.log(val, this.formData)
    },
    labelKeyPass(index) {
      return (rule, value, callback) => {
        if (value === '') {
          return callback(new Error('请输入标题名称'))
        } else {
          const same = this.formData.tem_content.label_info.findIndex(
            (p) => p.label_key === value
          )
          if (same !== -1 && same !== index) {
            return callback(new Error('输入标题名称不能重复'))
          } else {
            return callback()
          }
        }
      }
    },
    // 取消按钮
    close() {
      this.formData = {
        department_name: '',
        department_id: '',
        tem_content: {
          label_info: []
        }
      }
      this.selectDisabled = false
      this.$emit('closeSuccess')
      this.isOpen = false
    },
    // 打开弹框
    open() {
      this.isOpen = true
      this.getDepartmentList()
      this.getSysAllDic()
      // 判断创建还是编辑
      if (this.id) {
        this.selectDisabled = true
        this.getLookInfoModelDetail(this.id)
      }
    },
    /** 提交按钮 */
    submitForm() {
      const that = this
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 区分编辑与创建
          if (that.id) {
            editLookInfoModel(that.formData).then((res) => {
              if (res.code === 200) {
                that.$route.params.refresh = true
                that.close()
                that.$emit('createSuccess')
              } else {
                that.$message({
                  type: 'error',
                  message: res.msg,
                  duration: 1500
                })
              }
            })
          } else {
            creatLookInfoModel(that.formData).then((res) => {
              if (res.code === 200) {
                that.$route.params.refresh = true
                that.close()
                that.$emit('createSuccess')
              } else {
                that.$message({
                  type: 'error',
                  message: res.msg,
                  duration: 1500
                })
              }
            })
          }
        }
      })
    },
    // 获取部门列表
    getDepartmentList() {
      departmentList(this.queryParams).then((res) => {
        if (res.code === 200) {
          const list = this.dataOperation(res.data || [])
          this.deptOptions = list
        }
      })
    },
    // 已经创建了模板的部门添加disabled属性
    dataOperation(datas) {
      if (datas.length) {
        for (let i = 0; i < datas.length; i++) {
          if (this.listDepartmentId.includes(datas[i].id)) {
            datas[i].disabled = true
          }
          if (Object.hasOwnProperty.call(datas[i], 'children')) {
            this.dataOperation(datas[i]['children'])
          }
        }
      }
      return datas
    },
    getLookInfoModelDetail(id) {
      const that = this
      const datas = { id: id }
      departmentModelDetail(datas).then((res) => {
        if (res.code === 200) {
          that.detailsData = res.data
          that.formData = that.detailsData
          console.log(this.formData)
        }
      })
    },
    // 部门改变
    departmentChange(val) {
      const labels = this.$refs.department.getCheckedNodes()[0].label
      this.$set(this.formData, 'department_name', labels)
      console.log(val, labels, this.formData)
    },
    // 添加item
    addItem() {
      const items = {
        label_key: '',
        label_value: '',
        if_required: true,
        label_type: 'textarea',
        time_unix: new Date().getTime().toString(),
        select_info: []
      }
      this.formData.tem_content.label_info.push(items)
      this.$refs.form.clearValidate('tem_content.label_info')
    },
    removeItem(index) {
      this.formData.tem_content.label_info.splice(index, 1)
    }
  }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
.department-select {
  width: 100%;
}
::v-deep .name-form-item {
  margin-bottom: 0px;
}
::v-deep .el-checkbox.is-checked {
  .el-checkbox__label {
    color: #333;
  }
}
::v-deep .el-radio.is-checked {
  .el-radio__label {
    color: #333;
  }
}
</style>
